import { resetRouter } from '@/router'
import { RootState } from '@/store'
import { removeToken, setToken } from '@/utils/cookies'
import { ActionTree, Commit, Dispatch } from 'vuex'
import { UserMutationTypes } from './mutations'
import { UserState } from './state'

export enum UserActionTypes {
  ACTION_LOGIN = 'ACTION_LOGIN',
  ACTION_GET_USER_INFO = 'ACTION_GET_USER_INFO',
  ACTION_LOGIN_OUT = 'ACTION_LOGIN_OUT'
}
export interface UserActions {
  // 用户登录
  [UserActionTypes.ACTION_LOGIN](
    context: { commit: Commit; dispatch: Dispatch },
    userInfo: { username: string; password: string }
  ): Promise<Pick<UserState, 'token'>>

  // 获取用户信息
  [UserActionTypes.ACTION_GET_USER_INFO](context: {
    commit: Commit
  }): Promise<Omit<UserState, 'token'>>

  // 退出登录
  [UserActionTypes.ACTION_LOGIN_OUT](context: { commit: Commit }): Promise<null>
}

const actions: ActionTree<UserState, RootState> & UserActions = {
  // 登录
  [UserActionTypes.ACTION_LOGIN]({ commit }, userinfo) {
    console.log('userinfo')
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const res = {
          code: 1,
          data: {
            token: 'dsfsdflqwqhkdsfksbfsgdjbkjd'
          }
        }
        if (res.code === 1) {
          const token = res.data.token
          commit(UserMutationTypes.SET_TOKEN, token)
          setToken(token)
          resolve(res.data)
        } else {
          reject('登录出现了问题')
        }
      }, 3000)
    })
  },

  // 获取用户信息
  [UserActionTypes.ACTION_GET_USER_INFO]({ commit }) {
    return new Promise((resolve, reject) => {
      const roles = Math.random() > 0.5 ? ['admin'] : ['common']
      setTimeout(() => {
        const res = {
          code: 1,
          data: {
            name: '超级管理员',
            roles: roles
          }
        }
        console.log('响应值', res)
        if (res.code === 1) {
          const { name, roles } = res.data
          commit(UserMutationTypes.SET_NAME, name)
          commit(UserMutationTypes.SET_ROLES, roles)
          resolve(res.data)
        } else {
          reject('请求用户信息出现问题了')
        }
      }, 3000)
    })
  },

  // 退出
  [UserActionTypes.ACTION_LOGIN_OUT]({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        removeToken()
        commit(UserMutationTypes.SET_TOKEN)
        commit(UserMutationTypes.SET_ROLES)
        resetRouter()
      }, 1000)
    })
  }
}

export default actions
